from flask import Blueprint, request, jsonify
from app import db
from models.accounting import AccountingSubject, Voucher, VoucherEntry
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
import json

bp = Blueprint('finance', __name__, url_prefix='/api/finance')

@bp.route('/subjects', methods=['GET'])
@jwt_required()
def get_accounting_subjects():
    """获取会计科目列表"""
    try:
        subjects = AccountingSubject.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取会计科目列表成功',
            'data': [subject.to_dict() for subject in subjects]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取会计科目列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/subjects', methods=['POST'])
@jwt_required()
def create_accounting_subject():
    """创建会计科目"""
    try:
        data = request.get_json()
        
        # 检查必需字段
        required_fields = ['code', 'name', 'subject_type']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查科目编码是否已存在
        existing_subject = AccountingSubject.query.filter_by(code=data['code']).first()
        if existing_subject:
            return jsonify({
                'code': 400,
                'message': '科目编码已存在',
                'data': None
            }), 400
        
        # 创建新科目
        subject = AccountingSubject(
            code=data['code'],
            name=data['name'],
            subject_type=data['subject_type'],
            parent_id=data.get('parent_id'),
            is_leaf=data.get('is_leaf', False)
        )
        
        db.session.add(subject)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建会计科目成功',
            'data': subject.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建会计科目失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/vouchers', methods=['GET'])
@jwt_required()
def get_vouchers():
    """获取凭证列表"""
    try:
        # 获取查询参数
        period = request.args.get('period')
        status = request.args.get('status')
        
        # 构建查询
        query = Voucher.query.filter_by(is_deleted=False)
        
        if period:
            query = query.filter_by(period=period)
            
        if status:
            query = query.filter_by(status=status)
            
        vouchers = query.all()
        
        return jsonify({
            'code': 200,
            'message': '获取凭证列表成功',
            'data': [voucher.to_dict() for voucher in vouchers]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取凭证列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/vouchers/<int:voucher_id>', methods=['GET'])
@jwt_required()
def get_voucher(voucher_id):
    """获取凭证详情"""
    try:
        voucher = Voucher.query.get(voucher_id)
        if not voucher or voucher.is_deleted:
            return jsonify({
                'code': 404,
                'message': '凭证不存在',
                'data': None
            }), 404
            
        return jsonify({
            'code': 200,
            'message': '获取凭证详情成功',
            'data': voucher.to_dict()
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取凭证详情失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/vouchers', methods=['POST'])
@jwt_required()
def create_voucher():
    """创建凭证"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查必需字段
        required_fields = ['period', 'summary', 'entries']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 创建凭证
        voucher = Voucher(
            voucher_no=f"V{datetime.now().strftime('%Y%m%d%H%M%S')}",  # 简单的凭证号生成
            period=datetime.strptime(data['period'], '%Y-%m').date() if isinstance(data['period'], str) else data['period'],
            summary=data['summary'],
            created_by=current_user_id
        )
        
        db.session.add(voucher)
        db.session.flush()  # 获取voucher.id用于分录
        
        # 创建分录
        entries_data = data['entries']
        for entry_data in entries_data:
            entry = VoucherEntry(
                voucher_id=voucher.id,
                subject_id=entry_data['subject_id'],
                debit_amount=entry_data.get('debit_amount', 0),
                credit_amount=entry_data.get('credit_amount', 0),
                description=entry_data.get('description')
            )
            db.session.add(entry)
        
        db.session.commit()
        
        # 重新查询以获取完整数据（包括分录）
        voucher = Voucher.query.get(voucher.id)
        
        return jsonify({
            'code': 200,
            'message': '创建凭证成功',
            'data': voucher.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建凭证失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/vouchers/<int:voucher_id>/post', methods=['PUT'])
@jwt_required()
def post_voucher(voucher_id):
    """过账凭证"""
    try:
        voucher = Voucher.query.get(voucher_id)
        if not voucher:
            return jsonify({
                'code': 404,
                'message': '凭证不存在',
                'data': None
            }), 404
            
        if voucher.status != 'DRAFT':
            return jsonify({
                'code': 400,
                'message': '只有草稿状态的凭证可以过账',
                'data': None
            }), 400
            
        voucher.status = 'POSTED'
        voucher.posted_at = datetime.now()
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '凭证过账成功',
            'data': voucher.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'凭证过账失败: {str(e)}',
            'data': None
        }), 500